package com.spiderette.ace.sdk.bridge;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;

import com.spiderette.ace.sdk.SAceBusiness;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public class SAceCocosBridge implements SAceCocosIAP {

    private static SAceCocosBridge callbackApi;
    public static WeakReference<Activity> mainGameActivity;
    private Method evalString;
    private Method runOnGLThread;
    private static Handler handler = new Handler(Looper.getMainLooper());

    public static SAceCocosBridge getInstance() {
        if (callbackApi == null) {
            callbackApi = new SAceCocosBridge();
        }
        return callbackApi;
    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);

    }

    @Override
    public void XSSdkCallback(String action, String jsonData) {
        if (mainGameActivity != null && mainGameActivity.get() == null) {
            if (runOnGLThread==null){
                initRunOnGLThread();
            }
            if (evalString == null){
                initEvalString();
            }
            handler.post(() -> {
                try {
                    runOnGLThread.invoke(mainGameActivity.get(), new Runnable() {
                        @Override
                        public void run() {
                            try {
                                evalString.invoke(null, String.format("window.CCosCallback('%s','%s')", action, jsonData));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }


    private void initEvalString() {
        try {
            Class clzBridge = Class.forName(SAceBusiness.JJBPATH, false, SAceBusiness.context.getClassLoader());
            evalString = clzBridge.getDeclaredMethod("evalString", String.class);
            evalString.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initRunOnGLThread() {
        try {
            Class clzCocos2dAct = Class.forName(SAceBusiness.CAPATH, false, SAceBusiness.context.getClassLoader());
            runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread", Runnable.class);
            runOnGLThread.setAccessible(true);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
